package com.yunfatong.evidence.service;

import com.yunfatong.evidence.common.exception.CommonException;
import com.yunfatong.evidence.common.resultEnum.ResultCode;
import com.yunfatong.evidence.mapper.UserMasterMapperCustom;
import com.yunfatong.evidence.mapper.UserSlaveMapperCustom;
import com.yunfatong.evidence.model.UserMaster;
import com.yunfatong.evidence.model.UserSlave;
import com.yunfatong.evidence.model.UserSlaveExample;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 小客户service
 */
@Slf4j
@Service
public class UserSlaveService {

    @Autowired
    private UserSlaveMapperCustom userSlaveMapperCustom;

    @Autowired
    private UserMasterMapperCustom userMasterMapperCustom;

    /**
     * 根据 slave_code 获取UserSlave用户的信息
     *
     * @param slaveCode
     * @return
     */
    public UserSlave selectSlaveUserInfoBySlaveCode(String slaveCode, String masterCode) {
        if (StringUtils.isBlank(slaveCode) || StringUtils.isBlank(masterCode)) {
            return null;
        }
        UserSlaveExample example = new UserSlaveExample();
        example.createCriteria().andUserSlaveCodeEqualTo(slaveCode).andUserMasterCodeEqualTo(masterCode);
        List<UserSlave> selectByExample = userSlaveMapperCustom.selectByExample(example);
        if (null == selectByExample || selectByExample.size() < 1) {
            return null;
        } else if (selectByExample.size() > 1) {
            log.info("获取user_slave用户信息异常,根据user_slave_code获取 slave_user 获取到多条数据，应该为一条");
            throw new CommonException(ResultCode.OTHER_ERROR.getMsg(), ResultCode.OTHER_ERROR.getCode());
        } else {
            return selectByExample.get(0);
        }
    }

    @Transactional(rollbackFor = ArithmeticException.class, propagation = Propagation.REQUIRES_NEW)
    public void insertUserMaster() {
        UserMaster record = new UserMaster();
        record.setRemark("1");
        record.setStaffInfoId(1L);
        record.setUserMasterCode("1");
        record.setCreateTime(new Date());
        record.setUserMasterName("1");
        System.out.println(Thread.currentThread().getName());
        userMasterMapperCustom.insert(record);
        int i = 1 / 0;
    }
}
